package com.aizuda.boot.modules.third.openApi;


import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/open/enterprise")
@Tag(name = "企业信息API接口")
@Slf4j
public class EnterpriseApiController {

    @Value("${alicloud.appcode}")
    private String appcode;

    @Value("${alicloud.apis.enterprise.host:https://jisuqygsxx.market.alicloudapi.com}")
    private String host;

    @Value("${alicloud.apis.enterprise.path:/enterprise/query}")
    private String path;

    @Value("${alicloud.apis.enterprise.query-path:/enterprise/query}")
    private String queryPath;

    private final OkHttpClient httpClient;

    public EnterpriseApiController() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    @Operation(summary = "根据关键词查询企业信息")
    @GetMapping("/search")
    public SingleResponse<Map<String, Object>> searchEnterprise(
            @Parameter(description = "查询关键词", required = true)
            @RequestParam String keyword) {
        try {
            String encodedKeyword = URLEncoder.encode(keyword, StandardCharsets.UTF_8);
            String url = host + path + "?keyword=" + encodedKeyword;

            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Authorization", "APPCODE " + appcode)
                    .get()
                    .build();

            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    String responseBody = response.body().string();
                    Map<String, Object> resultMap = com.alibaba.fastjson.JSONObject.parseObject(responseBody, Map.class);
                    return SingleResponse.of(resultMap);
                } else {
                    log.error("企业信息查询失败，HTTP状态码: {}, 关键词: {}", response.code(), keyword);
                    return SingleResponse.failure(500, "企业信息查询失败");
                }
            }
        } catch (Exception e) {
            log.error("企业信息查询异常，关键词: {}, 错误信息: {}", keyword, e.getMessage(), e);
            return SingleResponse.failure(500, "网络请求异常: " + e.getMessage());
        }
    }

    @Operation(summary = "根据企业名称、统一社会信用代码或注册号查询企业详细信息")
    @GetMapping("/query")
    public SingleResponse<Map<String, Object>> queryEnterpriseInfo(
            @Parameter(description = "企业名称") @RequestParam(required = false) String company,
            @Parameter(description = "统一社会信用代码") @RequestParam(required = false) String creditno,
            @Parameter(description = "注册号") @RequestParam(required = false) String regno) {

        try {
            // 参数验证：至少需要提供一个查询条件
            if (!StringUtils.hasText(company) && !StringUtils.hasText(creditno) && !StringUtils.hasText(regno)) {
                return SingleResponse.failure(400, "请至少提供企业名称、统一社会信用代码或注册号中的一个参数");
            }

            // 构建URL查询参数
            StringBuilder urlBuilder = new StringBuilder(host + queryPath + "?");
            boolean hasParam = false;

            if (StringUtils.hasText(company)) {
                urlBuilder.append("company=").append(URLEncoder.encode(company.trim(), StandardCharsets.UTF_8));
                hasParam = true;
            }
            if (StringUtils.hasText(creditno)) {
                if (hasParam) urlBuilder.append("&");
                urlBuilder.append("creditno=").append(URLEncoder.encode(creditno.trim(), StandardCharsets.UTF_8));
                hasParam = true;
            }
            if (StringUtils.hasText(regno)) {
                if (hasParam) urlBuilder.append("&");
                urlBuilder.append("regno=").append(URLEncoder.encode(regno.trim(), StandardCharsets.UTF_8));
            }

            String requestUrl = urlBuilder.toString();
            log.info("企业信息查询请求URL: {}", requestUrl);
            log.info("使用AppCode: {}", appcode != null ? appcode.substring(0, Math.min(8, appcode.length())) + "..." : "null");

            // 构建GET请求
            Request request = new Request.Builder()
                    .url(requestUrl)
                    .addHeader("Authorization", "APPCODE " + appcode)
                    .get()
                    .build();

            // 执行请求
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.body() != null) {
                    String responseBody = response.body().string();
                    log.info("企业信息查询响应: HTTP状态码={}", response.code());
                    log.debug("企业信息查询响应体: {}", responseBody);

                    if (response.isSuccessful()) {
                        Map<String, Object> resultMap = com.alibaba.fastjson.JSONObject.parseObject(responseBody, Map.class);
                        return SingleResponse.of(resultMap);
                    } else {
                        // 尝试解析错误响应
                        try {
                            Map<String, Object> errorMap = com.alibaba.fastjson.JSONObject.parseObject(responseBody, Map.class);
                            String errorMsg = errorMap.getOrDefault("message", "企业信息查询失败").toString();
                            log.error("API返回错误: HTTP状态码={}, 错误信息={}", response.code(), errorMsg);
                            return SingleResponse.failure(response.code(), errorMsg + " (详细信息: " + responseBody + ")");
                        } catch (Exception e) {
                            log.error("解析错误响应失败: {}", responseBody);
                            return SingleResponse.failure(response.code(), "企业信息查询失败: " + responseBody);
                        }
                    }
                } else {
                    log.error("企业信息查询失败，响应体为空，HTTP状态码: {}", response.code());
                    return SingleResponse.failure(response.code(), "企业信息查询失败，响应体为空");
                }
            }
        } catch (Exception e) {
            log.error("企业信息查询异常，查询参数: company={}, creditno={}, regno={}, 错误信息: {}",
                    company, creditno, regno, e.getMessage(), e);
            return SingleResponse.failure(500, "网络请求异常: " + e.getMessage());
        }
    }
}